from django_redis import get_redis_connection
from rest_framework.generics import ListAPIView
from rest_framework.pagination import PageNumberPagination
from rest_framework_jwt.authentication import jwt_decode_handler

from GoldenSnow.serializers import UserModelSerializer, HotCitySerializer, HotEnterpriseSerializer, RecruitsSerializer, \
    SpitModelSerializer
from rest_framework.response import Response
from rest_framework.views import APIView

from GoldenSnow.utils import PageNumber
from xyz.models import City, User, Enterprise, Recruit, Spit


class UserCreateAPIView(APIView):

    def post(self, request):
        # 1.接收参数
        user_dict = request.data
        # 2.创建序列化器，并传递参数
        serializer = UserModelSerializer(data=user_dict)

        sms_code_client = user_dict.get('sms_code')
        mobile = user_dict.get('mobile')
        username = user_dict.get('username')
        try:
            if User.objects.filter(username=username):
                return Response('该用户名已注册', status=404)
            if User.objects.filter(mobile=mobile):
                return Response('该手机号已注册', status=404)
        except Exception as e:
            return Response('请重试', status=404)

        # 8.链接redis,获取redis的链接对象
        redis_conn = get_redis_connection('verify_code')

        # 9.从reids中,获取保存的短信验证码
        sms_code_server = redis_conn.get('sms_%s' % mobile)

        if not sms_code_server:
            return Response('短信验证码过期', status=404)

        # 10.把前后端的短信验证码进行比对
        if sms_code_client != sms_code_server.decode():
            return Response('输入的短信验证码错误', status=404)

        # 3.验证数据，并根据验证结果进行判断
        if serializer.is_valid():
            # 4.数据验证没有问题，调用序列化器的save方法。来触发序列化器的create方法
            # create方法会调用模型来保存到数据库中
            serializer.save()
            # 5. 返回响应 serializer.data 就是字典数据
            return Response(serializer.data)
        else:
            # 返回错误信息
            return Response('保存失败', status=404)


class HotCityListAPIView(ListAPIView):

    queryset = City.objects.filter(ishot=1)

    serializer_class = HotCitySerializer


class HotEnterpriseListAPIView(ListAPIView):

    queryset = Enterprise.objects.all().order_by('-visits')[0:6]

    serializer_class = HotEnterpriseSerializer

class RecommendRecruitsListAPIView(ListAPIView):
    queryset = Recruit.objects.all().order_by('-visits')[0:4]

    serializer_class = RecruitsSerializer


class LatestRecruitsListAPIView(ListAPIView):
    queryset = Recruit.objects.all().order_by('-createtime')[0:4]

    serializer_class = RecruitsSerializer

class SpitCollectAPIView(APIView):

    def put(self,request,id):

        try:
            token = self.request.auth
            toke_user = jwt_decode_handler(token)
            user_id = toke_user["user_id"]
        except Exception as e:
            return Response('收藏失败，请先登录',status=404)

        redis_conn = get_redis_connection('spit')
        # 判断key（'collect_%s' % id）中是否有value（user_id）
        if redis_conn.sismember('collect_%s' % id, user_id):
            redis_conn.srem('collect_%s' % id, user_id)
            spit = Spit.objects.get(id=id)
            return Response({
                'message': '取消收藏',
                'success': True
            })
        else:
            redis_conn.sadd('collect_%s' % id, user_id)
            spit = Spit.objects.get(id=id)
            return Response({
                'message':'收藏成功',
                'success':True
            })


class SpitThumbupAPIView(APIView):

    def put(self,request,id):

        try:
            token = self.request.auth
            toke_user = jwt_decode_handler(token)
            user_id = toke_user["user_id"]
        except Exception as e:
            return Response('点赞失败，请先登录', status=404)

        redis_conn = get_redis_connection('spit')
        # 判断key（'thumbup_%s' % id）中是否有value（user_id）
        if redis_conn.sismember('thumbup_%s' % id, user_id):
            redis_conn.srem('thumbup_%s' % id, user_id)
            spit = Spit.objects.get(id=id)
            spit.thumbup -= 1
            spit.save()
            return Response({
                'message': '取消点赞',
                'success': True
            })
        else:
            redis_conn.sadd('thumbup_%s' % id, user_id)
            spit = Spit.objects.get(id=id)
            spit.thumbup += 1
            spit.save()
            return Response({
                'message':'点赞成功',
                'success':True
            })


# class SpitListAPIView(ListAPIView):
#
#     queryset = Spit.objects.all().order_by('-publishtime')
#
#     serializer_class = SpitModelSerializer
#
#     pagination_class = PageNumber

